import { Breadcrumb } from 'antd'
import { useLocation } from 'react-router-dom'
import { useSelector } from 'react-redux'
import type { MenuItem } from '../../type/menu.ts'
import { useMemo } from 'react'

function findPath(path: string, menuList: Array<MenuItem>): Array<object> {
  const chiNameArr: Array<object> = []

  function findPathChiName(path: string, pathArr: Array<MenuItem>) {
    pathArr.forEach((item: MenuItem) => {
      if (path.startsWith(item.key)) {
        chiNameArr.push({ title: item.label })
        if (item.children) {
          findPathChiName(path, item.children)
        }
      }
    })
  }

  findPathChiName(path, menuList)
  return chiNameArr
}

export default function MyBreadcrumb() {
  const location = useLocation()
  const { menuList } = useSelector((state: any) => state.authSlice)

  // 使用useMemo来缓存数据，只有当location.pathname或者menuList改变时，才会导致面包屑的数据冲洗渲染
  const chiArr = useMemo(() => findPath(location.pathname, menuList), [location.pathname, menuList])
  return (
    <>
      <Breadcrumb items={chiArr} style={{ margin: '16px 0' }} />
    </>
  )
}
